use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

use crate::utils::current_datetime;

#[derive(Clone, Copy, Debug, PartialEq, Eq, DeriveValueType, Serialize, Deserialize)]
pub struct Id(pub i32);

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "cms_article")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    /// 所属专题
    pub topic_id: i32,
    /// 文章标题
    #[sea_orm(column_type = "String(StringLen::N(64))", indexed)]
    pub title: String,
    /// 作者
    #[sea_orm(column_type = "String(StringLen::N(32))")]
    pub author: String,
    /// 转载来源网址
    pub fromurl: String,
    /// 封面图
    pub image: String,
    /// 关键词
    pub keywords: String,
    /// 简介
    pub description: String,
    /// 是否允许评论
    pub allow_comments: bool,
    /// 状态
    /// - 0 待发布
    /// - 1 审核中
    /// - 2 已发布
    /// - 3 被驳回
    /// - `>=64` 回收站
    #[sea_orm(indexed)]
    pub status: u8,
    /// 发布人id
    #[sea_orm(indexed)]
    pub user_id: i32,
    /// 阅读数量
    pub read_number: u32,
    /// 内容
    #[sea_orm(column_type = "custom(\"LONGTEXT\")")]
    pub content: String,
    pub is_markdown: bool,
    #[sea_orm(indexed)]
    pub publish_at: chrono::NaiveDateTime,
    pub created_at: chrono::NaiveDateTime,
    pub updated_at: chrono::NaiveDateTime,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl Related<super::cms_category::Entity> for Entity {
    fn to() -> RelationDef {
        // The final relation is cms_article -> cms_article_category -> cms_category
        <super::cms_article_category::Entity as Related<super::cms_category::Entity>>::to()
    }

    fn via() -> Option<RelationDef> {
        // The original relation is cms_article_category -> cms_article,
        // after `rev` it becomes cms_article -> cms_article_category
        Some(<super::cms_article_category::Entity as Related<Entity>>::to().rev())
    }
}

impl Related<super::cms_article_category::Entity> for Entity {
    fn to() -> RelationDef {
        // The final relation is cms_article -> cms_article_category
        <super::cms_article_category::Entity as Related<Entity>>::to().rev()
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    /// Will be called before `ActiveModel::insert`, `ActiveModel::update`, and `ActiveModel::save`
    async fn before_save<C>(mut self, _: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        let current = current_datetime();
        if insert {
            self.created_at = sea_orm::Set(current);
        }
        self.updated_at = sea_orm::Set(current);
        Ok(self)
    }
}
